package svc

import (
	cmdb_account_management_rpc "dfx_cmdb/cmdb-account-management-rpc/types/cmdb-account-management-rpc"
	cmdb_blacklist_rpc "dfx_cmdb/cmdb-blacklist-rpc/types/cmdb-blacklist-rpc"
	"dfx_cmdb/cmdb-gateway/internal/config"
	"dfx_cmdb/common/loadetcdconfig"

	toolsdatabase "gitee.com/daofeixian/dfx_golang_toolset/databases"
	toolsloadetcd "gitee.com/daofeixian/dfx_golang_toolset/loadconfig"
	toolsnosql "gitee.com/daofeixian/dfx_golang_toolset/nosqls"
	configurator "github.com/zeromicro/go-zero/core/configcenter"
	"github.com/zeromicro/go-zero/core/configcenter/subscriber"
	"github.com/zeromicro/go-zero/zrpc"
	"gorm.io/gorm"
)

type ServiceContext struct {
	Config                   config.Config
	CmdbBlacklistRpc         cmdb_blacklist_rpc.BlacklistOperationClient
	IgnoreRuleOperation      cmdb_blacklist_rpc.IgnoreRuleOperationClient
	CmdbAccountManagementRpc cmdb_account_management_rpc.AccountManagementClient
	EDS                      subscriber.Subscriber
	EDC                      configurator.Configurator[loadetcdconfig.Config]
	DB                       *gorm.DB
	RC                       toolsnosql.RedisClient
}

func NewServiceContext(c config.Config) *ServiceContext {
	es, ec, v := toolsloadetcd.LoadETCDConfig[loadetcdconfig.Config](c.Etcds.Hosts, c.Etcds.LoadEtcdKey)

	var db *gorm.DB
	for _, v := range v.DatabasesConfig {
		if v.Name == "cmdb" {
			db = toolsdatabase.InitDBter(&v).InitDB()
		}
	}

	var rc toolsnosql.RedisClient
	for _, v := range v.RedisConfig {
		if v.Name == "cmdb" {
			rc = toolsnosql.InitNosqlter(&v).InitRedis()
		}
	}

	return &ServiceContext{
		Config:                   c,
		// CmdbBlacklistRpc:         cmdb_blacklist_rpc.NewBlacklistOperationClient(zrpc.MustNewClient(c.CmdbBlacklist).Conn()),
		// IgnoreRuleOperation:      cmdb_blacklist_rpc.NewIgnoreRuleOperationClient(zrpc.MustNewClient(c.CmdbBlacklist).Conn()),
		CmdbAccountManagementRpc: cmdb_account_management_rpc.NewAccountManagementClient(zrpc.MustNewClient(c.CmdbAccountManagement).Conn()),
		EDS:                      es,
		EDC:                      ec,
		DB:                       db,
		RC:                       rc,
	}
}
